# -*- coding: utf-8 -*-
"""
# @created on : 9月 2021/9/26 09:12
# @author     : kevin
# @file       : get_data.py
# @software   : PyCharm
# @project    : auto_keyword_data


@license: (C) Copyright 2019-2025, Corporation Limited.
@desc:
"""
import os
import re

import pandas as pd
from utils.excel import OperationExcel
from utils.path import OperationPath
from common.log import Logger
import yaml


class GetData:
    def __init__(self, sheet_name):
        self.excel = OperationExcel(sheet_name)
        self.log = Logger()
        self.path = OperationPath()

    def my_return(self, ret):
        """
        判断传入值是否为缺失值，不是就返回相应值，是则返回None
        :param ret: 传入值
        :return: 取值，缺失则返回None
        """
        flg = ''
        if pd.notnull(ret):
            flg = ret
        return flg

    def get_suit_lines(self):
        """
        获取所有的suit，保存成列表并返回
        :return: suit列表
        """
        lines =self.excel.get_lines()
        return lines

    def get_suits(self):
        suits = []
        try:
            data = self.excel.get_data()
            for i in range(len(data)):
                if not pd.isna(data.loc[i]['测试项目']):
                    suits.append({'测试项目': data.loc[i]['测试项目'],
                                 'sheet': data.loc[i]['用例sheetName'],
                                 'data': data.loc[i]['数据集'],
                                 'run': data.loc[i]['是否执行']})
        except ValueError as e:
            self.log.logger('error', f'读取suit数据失败，错误为：{e}')
        finally:
            return suits

    def get_case_data(self, sheet_name):
        """
        获取指定case用例，转成列表并返回
        :return: 单一sheet的case列表
        """
        self.excel = OperationExcel(sheet_name)
        cases = []
        try:
            data = self.excel.get_data()
            for i in range(len(data)):
                if not pd.isna(data.loc[i]['测试步骤']):
                    cases.append({'测试步骤': data.loc[i]['测试步骤'],
                                  '事件': data.loc[i]['事件'],
                                  '定位方式': data.loc[i]['定位方式'],
                                  '定位路径': data.loc[i]['定位路径'],
                                  '输入值': data.loc[i]['输入值'],
                                  '断言': data.loc[i]['断言'],
                                  '用例描述': data.loc[i]['用例描述']})
        except ValueError as e:
            cases = None
            self.log.logger('error', f'获取cese数据失败，错误为:{e}')
        finally:
            return cases

    def read_yaml(self, data_file):
        input_data = None
        data_path = os.path.join(self.path.get_current_path(), 'data')
        data_file_name = os.path.join(data_path, data_file + '.yaml')
        try:
            with open(data_file_name, encoding='utf-8') as f:
                input_data = yaml.safe_load(f)
        except TypeError as e:
            self.log.logger('error', f'读取yaml文件失败，错误信息为：{e}')
        return input_data

    def get_test_case(self):
        case = []
        input_key = ''
        suits = self.get_suits()
        for i in range(len(suits)):
            if suits[i]['run'] == 'Y':
                sheet_name = self.my_return(suits[i]['sheet'])
                data_file = self.my_return(suits[i]['data'])
                data_case = self.get_case_data(sheet_name=sheet_name)
                if data_file:
                    input_data = self.read_yaml(data_file)
                    if input_data:
                        for j in range(len(input_data)):
                            for k in range(len(data_case)):
                                if str(data_case[k]['输入值']).startswith('${') and str(data_case[k]['输入值']).endswith('}'):
                                    input_key = input_data[j][str(data_case[k]['输入值']).lstrip('${').rstrip('}')]
                                    case.append({'suit_name': self.my_return(suits[i]['测试项目']),
                                                 'case_step': self.my_return(data_case[k]['测试步骤']),
                                                 'methods': self.my_return(data_case[k]['事件']),
                                                 'key': self.my_return(data_case[k]['定位方式']),
                                                 'path': self.my_return(data_case[k]['定位路径']),
                                                 'value': self.my_return(input_key),
                                                 'assertion': False,
                                                'description': self.my_return(data_case[k]['用例描述'])})
                                elif str(data_case[k]['输入值']).startswith('{') and str(data_case[k]['输入值']).endswith('}'):
                                    assertion = input_data[j][str(data_case[k]['输入值']).lstrip('{').rstrip('}')]
                                    case.append({'suit_name': self.my_return(suits[i]['测试项目']),
                                                 'case_step': self.my_return(data_case[k]['测试步骤']),
                                                 'methods': self.my_return(data_case[k]['事件']),
                                                 'key': self.my_return(data_case[k]['定位方式']),
                                                 'path': self.my_return(data_case[k]['定位路径']),
                                                 'value': self.my_return(data_case[k]['输入值']),
                                                 'assertion': str(str(data_case[k]['输入值']).lstrip('{').rstrip(
                                                     '}') + '=' + assertion),
                                                'description': self.my_return(data_case[k]['用例描述'])})
                                else:
                                    case.append({'suit_name': self.my_return(suits[i]['测试项目']),
                                                 'case_step': self.my_return(data_case[k]['测试步骤']),
                                                 'methods': self.my_return(data_case[k]['事件']),
                                                 'key': self.my_return(data_case[k]['定位方式']),
                                                 'path': self.my_return(data_case[k]['定位路径']),
                                                 'value': self.my_return(data_case[k]['输入值']),
                                                 'assertion': False,
                                                 'description': self.my_return(data_case[k]['用例描述'])})
                    else:
                        for k in range(len(data_case)):
                            case.append({'suit_name': self.my_return(suits[i]['测试项目']),
                                         'case_step': self.my_return(data_case[k]['测试步骤']),
                                         'methods': self.my_return(data_case[k]['事件']),
                                         'key': self.my_return(data_case[k]['定位方式']),
                                         'path': self.my_return(data_case[k]['定位路径']),
                                         'value': self.my_return(data_case[k]['输入值']),
                                         'assertion': False,
                                         'description': self.my_return(data_case[k]['用例描述'])})
                else:
                    for k in range(len(data_case)):
                        case.append({'suit_name': self.my_return(suits[i]['测试项目']),
                                     'case_step': self.my_return(data_case[k]['测试步骤']),
                                     'methods': self.my_return(data_case[k]['事件']),
                                     'key': self.my_return(data_case[k]['定位方式']),
                                     'path': self.my_return(data_case[k]['定位路径']),
                                     'value': self.my_return(data_case[k]['输入值']),
                                     'assertion': False,
                                     'description': self.my_return(data_case[k]['用例描述'])})

        return case
